package me.stone.stanimeclient.core.common.extensions

import android.app.Activity
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.FrameMetrics
import android.view.Window
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner


enum class UnitEnum(val value: Long, val unitName: String) {
    S(1000000000L, "s"),
    MS(1000000L, "ms"),
    NS(1000L, "ns")
}

@RequiresApi(Build.VERSION_CODES.N)
fun Window.observeFrameMetrics(
    lifecycleOwner: LifecycleOwner,
    unit: UnitEnum = UnitEnum.MS
) {
    val listener = Window.OnFrameMetricsAvailableListener { _, metrics, _ ->
        val frameMetricsDisplay = """
            measure + layout = ${metrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) / unit.value}${unit.unitName},
            delay = ${metrics.getMetric(FrameMetrics.UNKNOWN_DELAY_DURATION) / unit.value}${unit.unitName},
            anim = ${metrics.getMetric(FrameMetrics.ANIMATION_DURATION) / unit.value}${unit.unitName},
            touch = ${metrics.getMetric(FrameMetrics.INPUT_HANDLING_DURATION) / unit.value}${unit.unitName},
            draw = ${metrics.getMetric(FrameMetrics.DRAW_DURATION) / unit.value}${unit.unitName},
            total = ${metrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) / unit.value}${unit.unitName}
        """.trimIndent().replace('\n', ' ')
        Log.d("frame", frameMetricsDisplay)
    }
    addOnFrameMetricsAvailableListener(listener, Handler(Looper.myLooper()!!))
    lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
        override fun onDestroy(owner: LifecycleOwner) {
            removeOnFrameMetricsAvailableListener(listener)
        }
    })
}